#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>

#include "debug.h"
#include "os_api.h"


#define _STACK_SIZE     (1024*3)

static void* _task_stack = NULL;

static OSTaskRef _task_ref = NULL;
static OSFlagRef _flag_ref = NULL;
static OSTimerRef _timer_ref = NULL;

#define TASK_TIMER_CHANGE_FLAG_BIT    0x01

static void _timer_callback(UINT32 tmrId)
{
    OSAFlagSet(_flag_ref, TASK_TIMER_CHANGE_FLAG_BIT, OSA_FLAG_OR);
	OSATimerStop(_timer_ref);
	OSATimerStart(_timer_ref, 30 * 200, 0, _timer_callback, 0); // 10s One-shot Timer 
}

static void _task_flag(void *ptr)
{
    OSA_STATUS status;
    UINT32 flag_value;
    UINT32 flag_mask = TASK_TIMER_CHANGE_FLAG_BIT;
    int count = 0;
				
    while(1) {
        status = OSAFlagWait(_flag_ref, flag_mask, OSA_FLAG_OR_CLEAR, &flag_value, OSA_SUSPEND);
		
		if (status == OS_SUCCESS){
			if (flag_value & TASK_TIMER_CHANGE_FLAG_BIT) {				
				count++;
				LOG_PRINTF("_task: count: %d\n", count);
			}
		}
    }
}



int main(void)
{	
    int ret;
	
    ret = OSAFlagCreate(&_flag_ref);
    ASSERT(ret == OS_SUCCESS);

    ret = OSATimerCreate(&_timer_ref);
    ASSERT(ret == OS_SUCCESS);

	_task_stack = malloc(_STACK_SIZE);
	ASSERT(_task_stack != NULL);

    ret = OSATaskCreate(&_task_ref, _task_stack, _STACK_SIZE, 120, "_task_flag", _task_flag, NULL);
    ASSERT(ret == OS_SUCCESS);

	LOG_PRINTF("OSATimerStart\n");	
	OSATimerStart(_timer_ref, 10 * 200, 0, _timer_callback, 0); // 10s One-shot Timer 
    //OSATimerStart(_timer_ref, 10 * 200, 10 * 200, _timer_callback, 0); // 10s Loop timer
	
	return 0;
}